import React, { useState, useEffect, useRef, useContext } from 'react';
import { Table, Button, Card, Row, Col, message, Modal, Form, Input, Select, Tag, Space, Spin } from 'antd';
import { PlusOutlined, ReloadOutlined, ExportOutlined, ImportOutlined, LeftOutlined, RightOutlined, ThunderboltOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useSpring, animated } from '@react-spring/web';
import { API_BASE_URL } from '../config';
import { TabsContext } from '../contexts/TabsContext';

// 产品版本模拟数据
const mockProductVersions = [
  {
    id: 1,
    product_id: 101,
    product_name: "智能门锁X1",
    version: "V01",
    version_desc: "初始版本",
    is_current: true,
    create_time: "2025-05-01 09:00:00",
    update_time: "2025-05-01 09:00:00",
    creator: "系统管理员"
  },
  {
    id: 2,
    product_id: 101,
    product_name: "智能门锁X1",
    version: "V02",
    version_desc: "增加了远程开锁功能",
    is_current: false,
    create_time: "2025-06-10 14:30:00",
    update_time: "2025-06-10 16:45:00",
    creator: "张工"
  },
  {
    id: 3,
    product_id: 102,
    product_name: "智能插座Pro",
    version: "V01",
    version_desc: "初始版本",
    is_current: true,
    create_time: "2025-07-01 11:20:00",
    update_time: "2025-07-01 11:20:00",
    creator: "李工"
  }
];

// 模板版本模拟数据
const mockTemplateVersions = [
  {
    id: 1,
    template_id: 101,
    template_code: 'TPL001',
    template_name: '21700圆柱电芯标准工艺',
    version: 'V001',
    version_desc: '初始版本',
    creator: '系统管理员',
    create_time: '2025-05-01 09:00:00',
    is_current: true
  },
  {
    id: 2,
    template_id: 102,
    template_code: 'TPL002',
    template_name: '方形电芯标准工艺',
    version: 'V001',
    version_desc: '初始版本',
    creator: '张工',
    create_time: '2025-06-10 14:30:00',
    is_current: true
  },
  {
    id: 3,
    template_id: 101,
    template_code: 'TPL001',
    template_name: '21700圆柱电芯标准工艺',
    version: 'V002',
    version_desc: '优化生产参数',
    creator: '李工',
    create_time: '2025-07-01 11:20:00',
    is_current: false
  }
];

// BOP版本模拟数据
const mockBOPVersions = [
  {
    id: 1,
    bop_id: 101,
    bop_code: 'BOPCY001012',
    bop_name: '21700圆柱电池BOP',
    version: 'V01',
    version_desc: '初始版本',
    creator: '系统管理员',
    create_time: '2025-05-01 09:00:00',
    is_current: true
  },
  {
    id: 2,
    bop_id: 102,
    bop_code: 'BOPFX001',
    bop_name: '方形电池BOP',
    version: 'V01',
    version_desc: '初始版本',
    creator: '张工',
    create_time: '2025-06-10 14:30:00',
    is_current: true
  },
  {
    id: 3,
    bop_id: 101,
    bop_code: 'BOPCY001012',
    bop_name: '21700圆柱电池BOP',
    version: 'V02',
    version_desc: '优化生产参数',
    creator: '李工',
    create_time: '2025-07-01 11:20:00',
    is_current: false
  }
];

const DataVersion = () => {
  const [activeTab, setActiveTab] = useState('productVersions');
  const [productVersions, setProductVersions] = useState([]);
  const [templateVersions, setTemplateVersions] = useState([]);
  const [bopVersions, setBOPVersions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentVersion, setCurrentVersion] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [isMobile, setIsMobile] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [allProductVersions, setAllProductVersions] = useState([]);
  const [allTemplateVersions, setAllTemplateVersions] = useState([]);
  const [allBOPVersions, setAllBOPVersions] = useState([]);
  const inputRef = useRef(null);
  
  // 动画效果
  const fadeAnimation = useSpring({
    from: { opacity: 0, transform: 'translateY(20px)' },
    to: { opacity: 1, transform: 'translateY(0)' },
    delay: 200,
  });
  
  // 智能补全分页大小
  const [modalPageSize, setModalPageSize] = useState(10);
  
  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);
  
  useEffect(() => {
    if (activeTab === 'productVersions') {
      fetchProductVersions();
    } else if (activeTab === 'templateVersions') {
      fetchTemplateVersions();
    } else if (activeTab === 'bopVersions') {
      fetchBOPVersions();
    }
  }, [activeTab]);
  
  // 更新当前页数据
  useEffect(() => {
    if (activeTab === 'productVersions' && allProductVersions.length > 0) {
      updatePageData(allProductVersions, currentPage);
    } else if (activeTab === 'templateVersions' && allTemplateVersions.length > 0) {
      updateTemplatePageData(allTemplateVersions, currentPage);
    } else if (activeTab === 'bopVersions' && allBOPVersions.length > 0) {
      updateBOPPageData(allBOPVersions, currentPage);
    }
  }, [currentPage, pageSize, allProductVersions, allTemplateVersions, allBOPVersions, activeTab]);
  
  // 手动分页处理
  const updatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setProductVersions(currentPageData);
  };
  
  const fetchProductVersions = async () => {
    setLoading(true);
    try {
      // 使用循环调用API获取所有产品版本数据
      let allItems = [];
      let currentPage = 1;
      const pageSize = 20; // 每页数据量，符合接口规范
      let hasMoreData = true;
      
      while (hasMoreData) {
        // 获取当前页的产品版本数据
        const response = await axios.get(`${API_BASE_URL}/api/product_version`, {
          params: {
            page: currentPage,
            size: pageSize
          }
        });
        
        if (response.data && response.data.code === 200) {
          const pageItems = response.data.data.items || [];
          const totalItems = response.data.data.total || 0;
          
          console.log(`获取产品版本数据，第${currentPage}页，数量:`, pageItems.length);
          
          // 将当前页数据添加到总列表中
          allItems = [...allItems, ...pageItems];
          
          // 判断是否还有更多数据
          if (pageItems.length === 0 || allItems.length >= totalItems) {
            hasMoreData = false;
          } else {
            currentPage++;
          }
        } else {
          message.error(`获取产品版本第${currentPage}页数据失败`);
          hasMoreData = false;
        }
      }
      
      console.log('获取到的产品版本总数量:', allItems.length);
      
      if (allItems.length > 0) {
        // 获取产品详细信息
        const productsWithDetails = await fetchProductDetails(allItems);
        
        setAllProductVersions(productsWithDetails);
        
        // 计算总数
        const total = productsWithDetails.length;
        setPagination({
          ...pagination,
          total: total
        });
        
        // 手动实现分页
        updatePageData(productsWithDetails, currentPage);
      } else {
        message.error('获取产品版本列表失败，显示模拟数据');
        setAllProductVersions(mockProductVersions);
        setPagination({
          ...pagination,
          total: mockProductVersions.length
        });
        updatePageData(mockProductVersions, currentPage);
      }
    } catch (error) {
      console.error('获取产品版本列表出错:', error);
      message.error('获取产品版本列表出错，显示模拟数据');
      setAllProductVersions(mockProductVersions);
      setPagination({
        ...pagination,
        total: mockProductVersions.length
      });
      updatePageData(mockProductVersions, currentPage);
    } finally {
      setLoading(false);
    }
  };
  
  // 获取产品详细信息
  const fetchProductDetails = async (versionItems) => {
    const productIds = [...new Set(versionItems.map(item => item.product_id))];
    const productDetailsMap = {};
    
    try {
      // 并行请求所有产品的详细信息
      const requests = productIds.map(id => 
        axios.get(`${API_BASE_URL}/api/product_info/${id}`)
      );
      
      const responses = await Promise.all(requests);
      
      // 创建产品ID到产品详细信息的映射
      responses.forEach(response => {
        if (response.data && response.data.code === 200) {
          const productData = response.data.data;
          productDetailsMap[productData.id] = productData;
        }
      });
      
      // 将产品详细信息添加到版本项中
      return versionItems.map(item => ({
        ...item,
        product_code: productDetailsMap[item.product_id]?.code || '-',
        product_name: productDetailsMap[item.product_id]?.name || item.product_name || '-'
      }));
    } catch (error) {
      console.error('获取产品详细信息出错:', error);
      return versionItems;
    }
  };
  
  const fetchTemplateVersions = async () => {
    setLoading(true);
    try {
      // 使用循环调用API获取所有模板版本数据
      let allItems = [];
      let currentPage = 1;
      const pageSize = 20; // 每页数据量，符合接口规范
      let hasMoreData = true;
      
      while (hasMoreData) {
        // 获取当前页的模板版本数据
        const response = await axios.get(`${API_BASE_URL}/api/process_template_version`, {
          params: {
            page: currentPage,
            size: pageSize
          }
        });
        
        if (response.data && response.data.code === 200) {
          const pageItems = response.data.data.items || [];
          const totalItems = response.data.data.total || 0;
          
          console.log(`获取模板版本数据，第${currentPage}页，数量:`, pageItems.length);
          
          // 将当前页数据添加到总列表中
          allItems = [...allItems, ...pageItems];
          
          // 判断是否还有更多数据
          if (pageItems.length === 0 || allItems.length >= totalItems) {
            hasMoreData = false;
          } else {
            currentPage++;
          }
        } else {
          message.error(`获取模板版本第${currentPage}页数据失败`);
          hasMoreData = false;
        }
      }
      
      console.log('获取到的模板版本总数量:', allItems.length);
      
      if (allItems.length > 0) {
        // 获取模板详细信息
        const templatesWithDetails = await fetchTemplateDetails(allItems);
        
        setAllTemplateVersions(templatesWithDetails);
        
        // 计算总数
        const total = templatesWithDetails.length;
        setPagination({
          ...pagination,
          total: total
        });
        
        // 手动实现分页
        updateTemplatePageData(templatesWithDetails, currentPage);
      } else {
        message.error('获取模板版本列表失败，显示模拟数据');
        setAllTemplateVersions(mockTemplateVersions);
        setPagination({
          ...pagination,
          total: mockTemplateVersions.length
        });
        updateTemplatePageData(mockTemplateVersions, currentPage);
      }
    } catch (error) {
      console.error('获取模板版本列表出错:', error);
      message.error('获取模板版本列表出错，显示模拟数据');
      setAllTemplateVersions(mockTemplateVersions);
      setPagination({
        ...pagination,
        total: mockTemplateVersions.length
      });
      updateTemplatePageData(mockTemplateVersions, currentPage);
    } finally {
      setLoading(false);
    }
  };
  
  // 手动分页处理 - 模板版本
  const updateTemplatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setTemplateVersions(currentPageData);
  };
  
  // 获取模板详细信息
  const fetchTemplateDetails = async (versionItems) => {
    const templateIds = [...new Set(versionItems.map(item => item.template_id))];
    const templateDetailsMap = {};
    
    try {
      // 并行请求所有模板的详细信息
      const requests = templateIds.map(id => 
        axios.get(`${API_BASE_URL}/api/process_template_info/${id}`)
      );
      
      const responses = await Promise.all(requests);
      
      // 创建模板ID到模板详细信息的映射
      responses.forEach(response => {
        if (response.data && response.data.code === 200) {
          const templateData = response.data.data;
          templateDetailsMap[templateData.id] = templateData;
        }
      });
      
      // 将模板详细信息添加到版本项中
      return versionItems.map(item => ({
        ...item,
        template_code: templateDetailsMap[item.template_id]?.code || '-',
        template_name: templateDetailsMap[item.template_id]?.name || '-'
      }));
    } catch (error) {
      console.error('获取模板详细信息出错:', error);
      return versionItems;
    }
  };
  
  // 手动分页处理 - BOP版本
  const updateBOPPageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setBOPVersions(currentPageData);
  };
  
  // 获取BOP版本列表
  const fetchBOPVersions = async () => {
    setLoading(true);
    try {
      // 使用循环调用API获取所有BOP版本数据
      let allItems = [];
      let currentPage = 1;
      const pageSize = 20; // 每页数据量，符合接口规范
      let hasMoreData = true;
      
      while (hasMoreData) {
        // 获取当前页的BOP版本数据
        const response = await axios.get(`${API_BASE_URL}/api/product_bop_version`, {
          params: {
            page: currentPage,
            size: pageSize
          }
        });
        
        if (response.data && response.data.code === 200) {
          const pageItems = response.data.data.items || [];
          const totalItems = response.data.data.total || 0;
          
          console.log(`获取BOP版本数据，第${currentPage}页，数量:`, pageItems.length);
          
          // 将当前页数据添加到总列表中
          allItems = [...allItems, ...pageItems];
          
          // 判断是否还有更多数据
          if (pageItems.length === 0 || allItems.length >= totalItems) {
            hasMoreData = false;
          } else {
            currentPage++;
          }
        } else {
          message.error(`获取BOP版本第${currentPage}页数据失败`);
          hasMoreData = false;
        }
      }
      
      console.log('获取到的BOP版本总数量:', allItems.length);
      
      if (allItems.length > 0) {
        // 获取BOP详细信息
        const bopsWithDetails = await fetchBOPDetails(allItems);
        
        setAllBOPVersions(bopsWithDetails);
        
        // 计算总数
        const total = bopsWithDetails.length;
        setPagination({
          ...pagination,
          total: total
        });
        
        // 手动实现分页
        updateBOPPageData(bopsWithDetails, currentPage);
      } else {
        message.error('获取BOP版本列表失败，显示模拟数据');
        setAllBOPVersions(mockBOPVersions);
        setPagination({
          ...pagination,
          total: mockBOPVersions.length
        });
        updateBOPPageData(mockBOPVersions, currentPage);
      }
    } catch (error) {
      console.error('获取BOP版本列表出错:', error);
      message.error('获取BOP版本列表出错，显示模拟数据');
      setAllBOPVersions(mockBOPVersions);
      setPagination({
        ...pagination,
        total: mockBOPVersions.length
      });
      updateBOPPageData(mockBOPVersions, currentPage);
    } finally {
      setLoading(false);
    }
  };
  
  // 获取BOP详细信息
  const fetchBOPDetails = async (versionItems) => {
    const bopIds = [...new Set(versionItems.map(item => item.bop_id))];
    const bopDetailsMap = {};
    
    try {
      // 并行请求所有BOP的详细信息
      const requests = bopIds.map(id => 
        axios.get(`${API_BASE_URL}/api/product_bop/${id}`)
      );
      
      const responses = await Promise.all(requests);
      
      // 创建BOP ID到BOP详细信息的映射
      responses.forEach(response => {
        if (response.data && response.data.code === 200) {
          const bopData = response.data.data;
          bopDetailsMap[bopData.id] = bopData;
        }
      });
      
      // 将BOP详细信息添加到版本项中
      return versionItems.map(item => ({
        ...item,
        bop_code: bopDetailsMap[item.bop_id]?.code || '-',
        bop_name: bopDetailsMap[item.bop_id]?.name || '-'
      }));
    } catch (error) {
      console.error('获取BOP详细信息出错:', error);
      return versionItems;
    }
  };
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    } catch (e) {
      return dateString;
    }
  };

  // 创建新产品版本
  const handleCreateProductVersion = () => {
    setCurrentVersion(null);
    form.resetFields();
    setEditModalVisible(true);
  };
  
  // 智能补全产品版本
  const [autoCompleteModalVisible, setAutoCompleteModalVisible] = useState(false);
  const [productsWithoutVersion, setProductsWithoutVersion] = useState([]);
  const [selectedProducts, setSelectedProducts] = useState([]);
  const [autoCompleteLoading, setAutoCompleteLoading] = useState(false);
  
  // 模态框分页相关状态
  const [modalCurrentPage, setModalCurrentPage] = useState(1);
  const [modalProducts, setModalProducts] = useState([]);
  const modalInputRef = useRef(null);
  
  // 更新模态框当前页数据
  const updateModalPageData = (data, page) => {
    if (!data || data.length === 0) return;
    const startIndex = (page - 1) * modalPageSize;
    const endIndex = startIndex + modalPageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setModalProducts(currentPageData);
  };
  
  // 处理模态框页码变化
  const handleModalPageChange = (page) => {
    setModalCurrentPage(page);
  };
  
  // 处理模态框页码输入
  const handleModalPageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(productsWithoutVersion.length / modalPageSize)) {
      setModalCurrentPage(value);
    }
  };
  
  // 处理模态框页码输入框按键事件
  const handleModalPageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(productsWithoutVersion.length / modalPageSize)) {
        setModalCurrentPage(value);
      }
    }
  };
  
  // 模态框前一页
  const goModalPrevPage = () => {
    if (modalCurrentPage > 1) {
      setModalCurrentPage(modalCurrentPage - 1);
    }
  };
  
  // 模态框后一页
  const goModalNextPage = () => {
    if (modalCurrentPage < Math.ceil(productsWithoutVersion.length / modalPageSize)) {
      setModalCurrentPage(modalCurrentPage + 1);
    }
  };
  
  // 更新模态框数据
  useEffect(() => {
    if (productsWithoutVersion.length > 0) {
      updateModalPageData(productsWithoutVersion, modalCurrentPage);
    }
  }, [modalCurrentPage, productsWithoutVersion, modalPageSize]);
  
  // 模态框分页样式
  const modalPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  // 处理智能补全按钮点击
  const handleAutoCompleteProductVersions = async () => {
    setAutoCompleteLoading(true);
    setModalCurrentPage(1); // 重置为第一页
    try {
      // 使用循环获取所有产品列表
      let allProducts = [];
      let productCurrentPage = 1;
      const productPageSize = 20; // 每页数据量
      let productHasMoreData = true;
      
      while (productHasMoreData) {
        const productResponse = await axios.get(`${API_BASE_URL}/api/product_info`, {
          params: {
            page: productCurrentPage,
            size: productPageSize
          }
        });
        
        if (productResponse.data && productResponse.data.code === 200) {
          const pageItems = productResponse.data.data.items || [];
          const totalItems = productResponse.data.data.total || 0;
          
          console.log(`获取产品列表，第${productCurrentPage}页，数量:`, pageItems.length);
          allProducts = [...allProducts, ...pageItems];
          
          if (pageItems.length === 0 || allProducts.length >= totalItems) {
            productHasMoreData = false;
          } else {
            productCurrentPage++;
          }
        } else {
          console.error('获取产品列表失败:', productResponse);
          productHasMoreData = false;
        }
      }
      
      console.log('获取到的产品总数:', allProducts.length);
      
      // 使用循环获取所有产品版本列表
      let allVersions = [];
      let versionCurrentPage = 1;
      const versionPageSize = 20; // 每页数据量
      let versionHasMoreData = true;
      
      while (versionHasMoreData) {
        const productVersionResponse = await axios.get(`${API_BASE_URL}/api/product_version`, {
          params: {
            page: versionCurrentPage,
            size: versionPageSize
          }
        });
        
        if (productVersionResponse.data && productVersionResponse.data.code === 200) {
          const pageItems = productVersionResponse.data.data.items || [];
          const totalItems = productVersionResponse.data.data.total || 0;
          
          console.log(`获取产品版本列表，第${versionCurrentPage}页，数量:`, pageItems.length);
          allVersions = [...allVersions, ...pageItems];
          
          if (pageItems.length === 0 || allVersions.length >= totalItems) {
            versionHasMoreData = false;
          } else {
            versionCurrentPage++;
          }
        } else {
          console.error('获取产品版本列表失败:', productVersionResponse);
          versionHasMoreData = false;
        }
      }
      
      console.log('获取到的产品版本总数:', allVersions.length);
      
      // 获取所有已有版本的产品ID
      const existingProductIds = new Set(allVersions.map(v => v.product_id));
      
      // 过滤出没有版本的产品
      const productsWithNoVersion = allProducts.filter(p => !existingProductIds.has(p.id));
      console.log('所有产品数量:', allProducts.length);
      console.log('有版本的产品数量:', existingProductIds.size);
      console.log('无版本的产品数量:', productsWithNoVersion.length);
      
      // 获取每个产品的详细信息，包括产品类别
      // 由于API可能存在限制，这里直接使用已有的产品信息，不再单独请求详情
      // 如果产品列表中已包含product_type字段则直接使用，否则设为默认值
      const productsWithDetails = productsWithNoVersion.map(product => ({
        ...product,
        product_type: product.product_type || '未分类'
      }));
      
      console.log('获取到详情的产品数量:', productsWithDetails.length);
      
      setProductsWithoutVersion(productsWithDetails);
      setSelectedProducts([]);
      setAutoCompleteModalVisible(true);
    } catch (error) {
      console.error('智能补全初始化错误:', error);
      message.error('获取产品列表出错');
    } finally {
      setAutoCompleteLoading(false);
    }
  };
  
  // 创建新模板版本
  const handleCreateTemplateVersion = () => {
    message.info('创建模板版本功能开发中...');
  };
  
  // 编辑产品版本
  const handleEditProductVersion = (record) => {
    setCurrentVersion(record);
    form.setFieldsValue({
      product_id: record.product_id,
      version: record.version,
      version_desc: record.version_desc
    });
    setEditModalVisible(true);
  };
  
  // 保存产品版本编辑
  const handleSaveEdit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentVersion) {
        // 更新版本
        const response = await axios.put(`${API_BASE_URL}/api/product_version/${currentVersion.id}`, values);
        if (response.data && response.data.code === 200) {
          message.success('产品版本更新成功');
          fetchProductVersions();
        } else {
          message.error('产品版本更新失败');
        }
      } else {
        // 创建新版本
        const response = await axios.post(`${API_BASE_URL}/api/product_version`, values);
        if (response.data && response.data.code === 200) {
          message.success('产品版本创建成功');
          fetchProductVersions();
        } else {
          message.error('产品版本创建失败');
        }
      }
      
      setEditModalVisible(false);
    } catch (error) {
      console.error('保存产品版本出错:', error);
      message.error('保存产品版本时出现错误');
    }
  };
  
  // 处理智能补全确认
  const handleAutoComplete = async () => {
    if (selectedProducts.length === 0) {
      message.warning('请至少选择一个产品');
      return;
    }
    
    setAutoCompleteLoading(true);
    try {
      // 为每个选中的产品创建初始版本
      const createPromises = selectedProducts.map(productId => {
        const product = productsWithoutVersion.find(p => p.id === productId);
        const versionData = {
          product_id: productId,
          version: 'V01',
          version_desc: '初始版本',
          is_current: true
        };
        
        return axios.post(`${API_BASE_URL}/api/product_version`, versionData)
          .catch(error => {
            console.error(`创建产品 ${product?.name || productId} 的版本失败:`, error);
            return { error: true, productId, productName: product?.name };
          });
      });
      
      const results = await Promise.all(createPromises);
      
      // 检查结果
      const successCount = results.filter(r => !r.error).length;
      const failedResults = results.filter(r => r.error);
      
      if (failedResults.length === 0) {
        message.success(`成功为 ${successCount} 个产品创建初始版本`);
      } else {
        const failedNames = failedResults.map(r => r.productName || r.productId).join(', ');
        message.warning(`${successCount} 个产品创建成功，${failedResults.length} 个失败: ${failedNames}`);
      }
      
      // 刷新产品版本列表
      fetchProductVersions();
      setAutoCompleteModalVisible(false);
    } catch (error) {
      console.error('批量创建产品版本出错:', error);
      message.error('批量创建产品版本时出现错误');
    } finally {
      setAutoCompleteLoading(false);
    }
  };
  
  // 设置为当前版本
  const handleSetCurrentVersion = async (record) => {
    try {
      const response = await axios.post(`${API_BASE_URL}/api/product_version/set_current/${record.id}`);
      if (response.data && response.data.code === 200) {
        message.success(`已将 ${record.version} 设为当前版本`);
        fetchProductVersions();
      } else {
        message.error('设置当前版本失败');
      }
    } catch (error) {
      console.error('设置当前版本出错:', error);
      message.error('设置当前版本时出现错误');
    }
  };
  
  // 导出版本数据
  const handleExportVersion = (record) => {
    message.info(`正在导出产品版本 ${record.version} 的数据...`);
    // 实现导出逻辑
  };
  
  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };
  
  // 引入TabsContext
  const { addTab } = useContext(TabsContext);
  
  // 处理跳转到产品详情页面
  const handleNavigateToProductDetail = (productId) => {
    if (productId) {
      // 使用TabsContext添加新标签页并跳转
      addTab(`product-${productId}`, '产品详情', 'ProductDetail', { productId });
    } else {
      message.warning('无法找到产品ID，无法跳转');
    }
  };
  
  // 产品版本表格列定义
  const productVersionColumns = [
    {
      title: '产品编码',
      dataIndex: 'product_code',
      key: 'product_code',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => handleNavigateToProductDetail(record.product_id)}>{text}</a>
      ),
    },
    {
      title: '产品名称',
      dataIndex: 'product_name',
      key: 'product_name',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => handleNavigateToProductDetail(record.product_id)}>{text}</a>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      render: (text, record) => {
        if (!record) return text;
        return (
          <a onClick={() => handleNavigateToProductDetail(record.product_id)}>
            {text}
            {record.is_current ? <Tag color="green">当前</Tag> : null}
          </a>
        );
      }
    },
    {
      title: '版本描述',
      dataIndex: 'version_desc',
      key: 'version_desc',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (text) => formatDate(text)
    }
  ];
  
  // 处理跳转到模板详情页面
  const handleNavigateToTemplateDetail = (templateId) => {
    if (templateId) {
      // 使用TabsContext添加新标签页并跳转
      addTab(`template-${templateId}`, '模板详情', 'ProcessTemplateDetail', { templateId });
    } else {
      message.warning('无法找到模板ID，无法跳转');
    }
  };
  
  // 模板版本表格列定义
  const templateVersionColumns = [
    {
      title: '模板编码',
      dataIndex: 'template_code',
      key: 'template_code',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => handleNavigateToTemplateDetail(record.template_id)}>{text}</a>
      ),
    },
    {
      title: '模板名称',
      dataIndex: 'template_name',
      key: 'template_name',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => handleNavigateToTemplateDetail(record.template_id)}>{text}</a>
      ),
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      render: (text, record) => {
        if (!record) return text;
        return (
          <a onClick={() => handleNavigateToTemplateDetail(record.template_id)}>
            {text}
            {record.is_current ? <Tag color="green">当前</Tag> : null}
          </a>
        );
      }
    },
    {
      title: '版本描述',
      dataIndex: 'version_desc',
      key: 'version_desc',
      ellipsis: true,
    },
    {
      title: '创建者',
      dataIndex: 'create_user',
      key: 'create_user',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (text) => formatDate(text)
    }
  ];
  
  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };
  
  // 获取行样式
  const getRowClassName = () => {
    if (productVersions.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 渲染产品版本表格
  const renderProductVersionTable = () => {
    return (
      <>
        <div className="action-bar">
          <div style={{ flex: 1 }}></div>
          <Button 
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={handleAutoCompleteProductVersions}
          >
            智能补全
          </Button>
          <Button 
            style={{ marginLeft: 8 }}
            icon={<ReloadOutlined />}
            onClick={() => fetchProductVersions()}
          >
            刷新
          </Button>
        </div>
        
        <div className="feature-list-container" style={{ height: 'calc(100% - 60px)', display: 'flex', flexDirection: 'column' }}>
          {loading ? (
            <div className="loading-container">
              <Spin>
                <div className="loading-content">加载中...</div>
              </Spin>
            </div>
          ) : (
            <>
              <div style={{ flex: 1, overflow: 'auto' }}>
                <Table
                  className={`data-table ${productVersions.length >= 10 || isMobile ? 'compact-table' : ''}`}
                  columns={productVersionColumns}
                  dataSource={productVersions}
                  rowKey="id"
                  pagination={false}
                  rowClassName={getRowClassName}
                  size={isMobile || productVersions.length >= 10 ? 'small' : 'middle'}
                  bordered={true}
                  scroll={{ x: isMobile ? 800 : 'max-content' }}
                  tableLayout="auto"
                  locale={{ emptyText: '暂无数据' }}
                />
              </div>
              
              {/* 自定义分页 */}
              <div style={customPaginationStyle}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <span>共 {pagination.total} 条</span>
                </div>
                
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Button 
                    icon={<LeftOutlined />}
                    onClick={goPrevPage}
                    disabled={currentPage === 1}
                    style={{ marginRight: '8px' }}
                  />
                  
                  <Input
                    ref={inputRef}
                    style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                    value={currentPage}
                    onChange={handlePageInputChange}
                    onKeyPress={handlePageInputKeyPress}
                  />
                  
                  <span style={{ margin: '0 8px' }}>
                    / {Math.ceil(pagination.total / pageSize)}
                  </span>
                  
                  <Button 
                    icon={<RightOutlined />}
                    onClick={goNextPage}
                    disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                    style={{ marginLeft: '8px', marginRight: '8px' }}
                  />
                  
                  <span style={{ marginLeft: '8px' }}>
                    {pageSize} / page
                  </span>
                </div>
              </div>
            </>
          )}
        </div>
      </>
    );
  };
  
  // 渲染模板版本表格
  const renderTemplateVersionTable = () => {
    return (
      <>
        <div className="action-bar">
          <div style={{ flex: 1 }}></div>
          <Button 
            style={{ marginLeft: 8 }}
            icon={<ReloadOutlined />}
            onClick={() => fetchTemplateVersions()}
          >
            刷新
          </Button>
        </div>
        
        <div className="feature-list-container" style={{ height: 'calc(100% - 60px)', display: 'flex', flexDirection: 'column' }}>
          {loading ? (
            <div className="loading-container">
              <Spin>
                <div className="loading-content">加载中...</div>
              </Spin>
            </div>
          ) : (
            <>
              <div style={{ flex: 1, overflow: 'auto' }}>
                <Table
                  className={`data-table ${templateVersions.length >= 10 || isMobile ? 'compact-table' : ''}`}
                  columns={templateVersionColumns}
                  dataSource={templateVersions}
                  rowKey="id"
                  pagination={false}
                  rowClassName={getRowClassName}
                  size={isMobile || templateVersions.length >= 10 ? 'small' : 'middle'}
                  bordered={true}
                  scroll={{ x: isMobile ? 800 : 'max-content' }}
                  tableLayout="auto"
                  locale={{ emptyText: '暂无数据' }}
                />
              </div>
              
              {/* 自定义分页 */}
              <div style={customPaginationStyle}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <span>共 {allTemplateVersions.length} 条</span>
                </div>
                
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Button 
                    icon={<LeftOutlined />}
                    onClick={goPrevPage}
                    disabled={currentPage === 1}
                    style={{ marginRight: '8px' }}
                  />
                  
                  <Input
                    ref={inputRef}
                    style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                    value={currentPage}
                    onChange={handlePageInputChange}
                    onKeyPress={handlePageInputKeyPress}
                  />
                  
                  <span style={{ margin: '0 8px' }}>
                    / {Math.ceil(allTemplateVersions.length / pageSize)}
                  </span>
                  
                  <Button 
                    icon={<RightOutlined />}
                    onClick={goNextPage}
                    disabled={currentPage >= Math.ceil(allTemplateVersions.length / pageSize)}
                    style={{ marginLeft: '8px', marginRight: '8px' }}
                  />
                  
                  <span style={{ marginLeft: '8px' }}>
                    {pageSize} / page
                  </span>
                </div>
              </div>
            </>
          )}
        </div>
      </>
    );
  };
  
  // 打开BOP详情
  const handleNavigateToBOPDetail = (bopId) => {
    if (!bopId) return;
    
    // 获取BOP信息
    const bopVersion = allBOPVersions.find(v => v.bop_id === bopId);
    if (!bopVersion) return;
    
    // 打开一个新的页签，用于展示BOP详情
    const tabKey = `bopDetail-${bopId}`;
    const tabTitle = `${bopVersion.bop_code || 'BOP'}`;
    
    // 使用BOPDetail组件而不是ProductBOP
    console.log('打开BOP详情:', bopId, bopVersion.bop_code);
    addTab(tabKey, tabTitle, 'BOPDetail', { bopId: bopId, code: bopVersion.bop_code });
  };
  
  // 渲染BOP版本表格
  const renderBOPVersionTable = () => {
    return (
      <>
        <div className="action-bar">
          <div style={{ flex: 1 }}></div>
          <Button 
            style={{ marginLeft: 8 }}
            icon={<ReloadOutlined />}
            onClick={() => fetchBOPVersions()}
          >
            刷新
          </Button>
        </div>
        
        <div className="feature-list-container" style={{ height: 'calc(100% - 60px)', display: 'flex', flexDirection: 'column' }}>
          {loading ? (
            <div className="loading-container">
              <Spin>
                <div className="loading-content">加载中...</div>
              </Spin>
            </div>
          ) : (
            <>
              <div style={{ flex: 1, overflow: 'auto' }}>
                <Table
                  className={`data-table ${bopVersions.length >= 10 || isMobile ? 'compact-table' : ''}`}
                  columns={[
                    {
                      title: 'BOP编码',
                      dataIndex: 'bop_code',
                      key: 'bop_code',
                      ellipsis: true,
                      render: (text, record) => (
                        <a onClick={() => handleNavigateToBOPDetail(record.bop_id)}>{text}</a>
                      )
                    },
                    {
                      title: 'BOP名称',
                      dataIndex: 'bop_name',
                      key: 'bop_name',
                      ellipsis: true,
                      render: (text, record) => (
                        <a onClick={() => handleNavigateToBOPDetail(record.bop_id)}>{text}</a>
                      )
                    },
                    {
                      title: '版本',
                      dataIndex: 'version',
                      key: 'version',
                      render: (text, record) => (
                        <span>
                          {text}
                          {record.is_current && (
                            <Tag color="green" style={{ marginLeft: 8 }}>当前版本</Tag>
                          )}
                        </span>
                      )
                    },
                    {
                      title: '版本描述',
                      dataIndex: 'version_desc',
                      key: 'version_desc',
                      ellipsis: true
                    },
                    {
                      title: '创建人',
                      dataIndex: 'creator',
                      key: 'creator'
                    },
                    {
                      title: '创建时间',
                      dataIndex: 'create_time',
                      key: 'create_time',
                      render: (text) => formatDate(text)
                    }
                  ]}
                  dataSource={bopVersions}
                  rowKey="id"
                  pagination={false}
                  rowClassName={getRowClassName}
                  size={isMobile || bopVersions.length >= 10 ? 'small' : 'middle'}
                  bordered={true}
                  scroll={{ x: isMobile ? 800 : 'max-content' }}
                  tableLayout="auto"
                  locale={{ emptyText: '暂无数据' }}
                />
              </div>
              
              {/* 自定义分页 */}
              <div style={customPaginationStyle}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <span>共 {pagination.total} 条</span>
                </div>
                
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Button 
                    icon={<LeftOutlined />}
                    onClick={goPrevPage}
                    disabled={currentPage === 1}
                    style={{ marginRight: '8px' }}
                  />
                  
                  <Input
                    ref={inputRef}
                    style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                    value={currentPage}
                    onChange={handlePageInputChange}
                    onKeyPress={handlePageInputKeyPress}
                  />
                  
                  <span style={{ margin: '0 8px' }}>
                    / {Math.ceil(pagination.total / pageSize)}
                  </span>
                  
                  <Button 
                    icon={<RightOutlined />}
                    onClick={goNextPage}
                    disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                    style={{ marginLeft: '8px', marginRight: '8px' }}
                  />
                  
                  <span style={{ marginLeft: '8px' }}>
                    {pageSize} / page
                  </span>
                </div>
              </div>
            </>
          )}
        </div>
      </>
    );
  };
  
  // 根据选项卡渲染内容
  const renderContent = () => {
    if (activeTab === 'productVersions') {
      return renderProductVersionTable();
    } else if (activeTab === 'templateVersions') {
      return renderTemplateVersionTable();
    } else if (activeTab === 'bopVersions') {
      return renderBOPVersionTable();
    }
    return null;
  };
  
  return (
    <div className="data-version">
      <div className="page-header">
        <div className="tab-container">
          <div className="tabs">
            <div 
              className={`tab-item ${activeTab === 'productVersions' ? 'active' : ''}`}
              onClick={() => setActiveTab('productVersions')}
            >
              产品版本
            </div>
            <div 
              className={`tab-item ${activeTab === 'templateVersions' ? 'active' : ''}`}
              onClick={() => setActiveTab('templateVersions')}
            >
              模板版本
            </div>
            <div 
              className={`tab-item ${activeTab === 'bopVersions' ? 'active' : ''}`}
              onClick={() => setActiveTab('bopVersions')}
            >
              BOP版本
            </div>
          </div>
        </div>
      </div>
      
      <div className="content-body">
        {renderContent()}
      </div>
      
      {/* 编辑产品版本对话框 */}
      <Modal
        title={currentVersion ? '编辑产品版本' : '新建产品版本'}
        open={editModalVisible}
        onOk={handleSaveEdit}
        onCancel={() => setEditModalVisible(false)}
        maskClosable={false}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="product_id"
            label="产品ID"
            rules={[{ required: true, message: '请输入产品ID' }]}
          >
            <Input placeholder="请输入产品ID" />
          </Form.Item>
          
          <Form.Item
            name="version"
            label="版本"
            rules={[{ required: true, message: '请输入版本号' }]}
          >
            <Input placeholder="请输入版本号，如V01" />
          </Form.Item>
          
          <Form.Item
            name="version_desc"
            label="版本描述"
          >
            <Input.TextArea placeholder="请输入版本描述" rows={4} />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 智能补全对话框 */}
      <Modal
        title="智能补全产品版本"
        open={autoCompleteModalVisible}
        onOk={handleAutoComplete}
        onCancel={() => setAutoCompleteModalVisible(false)}
        maskClosable={false}
        okText="确认"
        cancelText="取消"
        okButtonProps={{ disabled: selectedProducts.length === 0 }}
        width={800}
      >
        {autoCompleteLoading ? (
          <div style={{ textAlign: 'center', padding: '30px' }}>
            <Spin>
              <div style={{ padding: '30px', textAlign: 'center' }}>加载中...</div>
            </Spin>
          </div>
        ) : (
          <>
            <div style={{ marginBottom: 16 }}>
              <p>以下产品尚未创建版本信息，请选择需要自动创建版本的产品：</p>
              {productsWithoutVersion.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                  所有产品已经创建了版本信息
                </div>
              ) : (
                <>
                  <Table
                    rowSelection={{
                      type: 'checkbox',
                      selectedRowKeys: selectedProducts,
                      onChange: (selectedRowKeys) => setSelectedProducts(selectedRowKeys)
                    }}
                    columns={[
                      {
                        title: '产品编码',
                        dataIndex: 'code',
                        key: 'code',
                        width: 120
                      },
                      {
                        title: '产品名称',
                        dataIndex: 'name',
                        key: 'name',
                        width: 180
                      },
                      {
                        title: '产品型号',
                        dataIndex: 'model',
                        key: 'model',
                        width: 120
                      },
                      {
                        title: '产品类别',
                        dataIndex: 'product_type',
                        key: 'product_type',
                        width: 100
                      },
                      {
                        title: '创建时间',
                        dataIndex: 'create_time',
                        key: 'create_time',
                        render: (text) => formatDate(text)
                      }
                    ]}
                    dataSource={modalProducts}
                    rowKey="id"
                    pagination={false}
                    size="small"
                    scroll={{ y: 300 }}
                  />
                  
                  {/* 模态框自定义分页 */}
                  <div style={modalPaginationStyle}>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <span>共 {productsWithoutVersion.length} 条</span>
                    </div>
                    
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <Button 
                        icon={<LeftOutlined />}
                        onClick={goModalPrevPage}
                        disabled={modalCurrentPage === 1}
                        style={{ marginRight: '8px' }}
                      />
                      
                      <Input
                        ref={modalInputRef}
                        style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                        value={modalCurrentPage}
                        onChange={handleModalPageInputChange}
                        onKeyPress={handleModalPageInputKeyPress}
                      />
                      
                      <span style={{ margin: '0 8px' }}>
                        / {Math.ceil(productsWithoutVersion.length / modalPageSize)}
                      </span>
                      
                      <Button 
                        icon={<RightOutlined />}
                        onClick={goModalNextPage}
                        disabled={modalCurrentPage >= Math.ceil(productsWithoutVersion.length / modalPageSize)}
                        style={{ marginLeft: '8px', marginRight: '8px' }}
                      />
                      
                      <span style={{ marginLeft: '8px' }}>
                        {modalPageSize} / page
                      </span>
                    </div>
                  </div>
                </>
              )}
            </div>
            <div style={{ color: '#1890ff', marginTop: 8 }}>
              <p>将为选中产品创建初始版本"V01"</p>
            </div>
          </>
        )}
      </Modal>
      
      <style>{`
        .data-version {
          padding: 16px;
          height: 100%;
          display: flex;
          flex-direction: column;
        }
        
        .page-header {
          margin-bottom: 24px;
        }
        
        .tab-container {
          border-bottom: 1px solid #e8e8e8;
          margin-bottom: 16px;
        }
        
        .tabs {
          display: flex;
          flex-direction: row;
        }
        
        .tab-item {
          padding: 12px 16px;
          margin-right: 24px;
          font-size: 16px;
          cursor: pointer;
          position: relative;
        }
        
        .tab-item.active {
          color: #1890ff;
          font-weight: 500;
        }
        
        .tab-item.active:after {
          content: "";
          position: absolute;
          left: 0;
          bottom: -1px;
          width: 100%;
          height: 2px;
          background-color: #1890ff;
        }
        
        .action-bar {
          margin: 16px 0;
          display: flex;
          justify-content: flex-end;
        }
        
        .content-body {
          flex: 1;
          overflow-y: auto;
        }
        
        .loading-container {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 200px;
        }
        
        .loading-content {
          padding-top: 40px;
          text-align: center;
        }
        
        .data-table {
          margin: 0;
        }
        
        .data-table.compact-table .ant-table-thead > tr > th {
          padding: 8px;
        }
        
        .table-row-normal-height {
          height: 54px;
        }
        
        .table-row-compact-height {
          height: 40px;
        }
        
        .compact-table .ant-table-tbody > tr > td {
          padding: 6px 8px;
        }
      `}</style>
    </div>
  );
};

export default DataVersion; 